package jp.dodododo.xml.impl;

import java.io.IOException;
import java.io.InputStream;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import jp.dodododo.xml.DtdPathSet;
import jp.dodododo.xml.Parser;
import jp.dodododo.xml.exception.XmlRuntimeException;

import org.xml.sax.SAXException;

public class ParserImpl implements Parser {

	public <T> T parse(InputStream is, Class<T> clazz, DtdPathSet dtdPathSet, boolean validating) throws XmlRuntimeException {
		try {
			SAXParserFactory saxFactory = SAXParserFactory.newInstance();
			saxFactory.setValidating(validating);
			SAXParser parser = saxFactory.newSAXParser();
			Handler<T> handler = new Handler<T>(clazz, dtdPathSet);
			parser.parse(is, handler);
			return handler.getResult();
		} catch (ParserConfigurationException e) {
			throw new XmlRuntimeException(e);
		} catch (SAXException e) {
			throw new XmlRuntimeException(e);
		} catch (IOException e) {
			throw new XmlRuntimeException(e);
		}
	}

	public <T> T parse(InputStream is, Class<T> clazz) throws XmlRuntimeException {
		return parse(is, clazz, false);
	}

	public <T> T parse(InputStream is, Class<T> clazz, boolean validating) throws XmlRuntimeException {
		return parse(is, clazz, new DtdPathSet(), validating);
	}

	public <T> T parse(InputStream is, Class<T> clazz, DtdPathSet dtdPathSet) throws XmlRuntimeException {
		return parse(is, clazz, dtdPathSet, false);
	}

}
